package com.gis.controller;

import java.util.HashMap;
import java.util.Map;

import com.gis.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gis.result.ResponseResult;
import com.gis.annotation.RequirePermission;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 请求处理前进行拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取 token 或 session
        String token = request.getHeader("Authorization"); // 示例使用 Authorization header

        if (token == null || !isValidToken(token)) {
            // 返回未登录错误
            Map<String, Object> data = new HashMap<>();
            data.put("code", 401);
            data.put("message", "未登录");
            String json = new ObjectMapper().writeValueAsString(ResponseResult.fail(data));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false; // 拦截请求
        }

        // 检查权限
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequirePermission requirePermission = handlerMethod.getMethodAnnotation(RequirePermission.class);

            if (requirePermission != null) {
                String requiredPermission = requirePermission.value();
                String userType = JwtUtil.parseUserType(token);

                // 如果接口需要管理员权限，但用户不是管理员
                if ("admin".equals(requiredPermission) && !"admin".equals(userType)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("code", 403);
                    data.put("message", "权限不足，需要管理员权限");
                    String json = new ObjectMapper().writeValueAsString(ResponseResult.fail(data));
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(json);
                    return false;
                }
            }
        }

        return true; // 放行
    }

    /**
     * 验证 token 是否有效
     */
    private boolean isValidToken(String token) {
        return JwtUtil.validateToken(token);
    }

}

